# -*- coding: utf-8 -*
from flask import Flask,request
import sys
from docx import shared
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx import Document
from docx.shared import Inches
from lxml import etree
import time
import base64
from io import BytesIO
from PIL import Image
app = Flask(__name__)

@app.route("/")
def index():
    return 'hello word'

@app.post("/export_word")
def export_word_post():
    try:
        # mathml_output = sys.argv[1]
        # print(mathml_output)
        # print(mathml_output)
        # MML2OMML.XSL
        mathml_output = request.form['data']
        base64_string = request.form['img']
        tree = etree.fromstring(mathml_output)
        xslt = etree.parse('MML2OMML.XSL')
        transform = etree.XSLT(xslt)
        new_dom = transform(tree)
        
        doc = Document()
        doc.styles['Normal'].font.name = 'Arial'
        # 定义中文文字字体
        # doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
        # 定义字体大小
        doc.styles['Normal'].font.size = shared.Pt(12)
        doc.styles['Normal'].italic = False
        image_data = base64.b64decode(base64_string)
        image_stream = BytesIO(image_data)
        image = Image.open(image_stream)

        # Calculate aspect ratio if height is not
        aspect_ratio = image.width / image.height
        height = Inches(6.0) / aspect_ratio

        # Add image to the Word document
        doc.add_picture(image_stream, Inches(6.0), height)
        paragraph = doc.add_paragraph('')
        paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
        paragraph._element.append(new_dom.getroot())
        timestamp = time.time()
        local_time = time.localtime(timestamp)
        format_date = time.strftime("%Y%m%d", local_time)
        docx_path = 'doc/{}.docx'.format(format_date+str(timestamp))
        doc.save(docx_path)
        return {'code':200, 'msg':'导出成功', 'path':docx_path}
    except AssertionError as msg:
        print(msg)